package com.ysmygx.service.impl;

import cn.hutool.http.Header;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSON;
import com.ysmygx.dto.InteractionDto;
import com.ysmygx.entity.BankServiceBody;
import com.ysmygx.entity.BankServiceResp;
import com.ysmygx.service.BankInteraction;
import com.ysmygx.utils.BusinessException;
import com.ysmygx.utils.ThreadLocalUtil;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

/**
 * 支付服务，
 */
@Log4j2
@Service
public class BankInteractionImpl implements BankInteraction {
    @Value("${pay.bank-sn}")
    private String bankCertSN;

    /**
     *
     * @param interactionDto
     * @return 返回加密的处理结果
     */
    @Override
    public String interaction(InteractionDto interactionDto) {
        BankServiceBody bankServiceBody = new BankServiceBody();
        bankServiceBody.setBankCertSN(bankCertSN);
        bankServiceBody.setSignData(interactionDto.getSignData());
        bankServiceBody.setCiphertext(interactionDto.getCiphertext());
        String bankServiceBodyJson = JSON.toJSONString(bankServiceBody);

        HttpResponse response = HttpRequest.post(interactionDto.getUrl())
                .header(Header.CONTENT_TYPE, "application/json")
                .header("Accept-Encoding", "*")
                .body(bankServiceBodyJson)
                .execute();

        BankServiceResp bankServiceResp = null;
        if (response.isOk()){
            String respBody = response.body();
            bankServiceResp = JSON.parseObject(respBody, BankServiceResp.class);
        }else{
            log.error("链路：{},interaction方法响应异常：{}", ThreadLocalUtil.get(), JSONUtil.toJsonStr(response));
            throw new BusinessException(JSONUtil.toJsonStr(response));
        }

//        log.info(bankServiceResp);

        return bankServiceResp.getData();
    }
}


